package com.common.myspring.core.proxy;

import com.common.myspring.annotation.LogAnnotation;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * @title: JdkProxy
 * @Author xu-xiang
 * @Date: 2023/8/30 16:57
 * @description:
 */
public class CglibProxy_bak<T> implements MethodInterceptor {

    private final T bean;

    public CglibProxy_bak(T bean) {
        this.bean = bean;
    }

    @SuppressWarnings("unchecked")
    public T doProxy() {
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(bean.getClass());
        enhancer.setCallback(this);
        return (T) enhancer.create();
    }

    public static <T> T createProxyObject(T bean) {
        return new CglibProxy_bak<>(bean).doProxy();
    }


    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        if (!method.isAnnotationPresent(LogAnnotation.class)) {
            return method.invoke(bean, objects);
        }

        System.out.println("Cglib代理方法" + method.getName() + "执行开始!");
        Object proceed = method.invoke(bean, objects);
        System.out.println("Cglib代理方法" + method.getName() + "执行结束!\n");
        return proceed;
    }
}
